package com.soap.controller;

import com.soap.common.HttpJsonResult;
import com.soap.config.LayuiPage;
import me.huqiao.loganlyzer.AnalysisUtil;
import me.huqiao.loganlyzer.console.ShowHeadMsg;
import me.huqiao.loganlyzer.util.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
@RequestMapping("/log")
public class AccessLogController {
    private static Logger log = LoggerFactory.getLogger(AccessLogController.class);
    /**
     * 主页
     */
    @RequestMapping("/index")
    public String loginCreate()
    {
        return "index";
    }

    /**
     * 进入到分析页面
     * @return
     */
    @RequestMapping("/toAnalysis")
    public String toAnalysis()
    {
        return "analysis";
    }

    /*
     * 上传数据 也没限制
     */
    @PostMapping("/uplod")
    @ResponseBody
    public HttpJsonResult uploadLog(@RequestParam(required = true)MultipartFile file, @RequestParam(value = "logPattern",required = true)String logPattern, HttpServletRequest request) throws IOException {
        HttpJsonResult httpJsonResult=new HttpJsonResult();
        StringBuilder sb=new StringBuilder();
        if(null==file || file.isEmpty()){
            sb.append("上传文件为空!");
        }

        if(StringUtils.isEmpty(logPattern)){
            sb.append("日志格式未填写!");
        }

        if(sb.toString().length()>0 || "null".equals(sb.toString())){
            httpJsonResult.setJsonCode(-1);
            httpJsonResult.setJsonMsg(sb.toString());
            return httpJsonResult;
        }

        //跟新内容扫描器
        AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
        analysisUtil.initScaner(FileUtil.readContentByLine(file));
        analysisUtil.setLogPattern(logPattern);
        return httpJsonResult;
    }

    //解析跳转
    @PostMapping("/logPatterns")
    @ResponseBody
    public HttpJsonResult logPatterns() throws Exception {
        Map<String,Object> queryMap=new HashMap<>();
        HttpJsonResult httpJsonResult=new HttpJsonResult();
        String[] logPatterns=AnalysisUtil.getInstance().getHeadMsg().getLogPatterns();
        if(null!=logPatterns) {
            List<Map<String,String>> headMsg=new ArrayList<>();
            List<Map<String,String>> body=new ArrayList<>();
            //Map<String,String>temp2=new HashMap<>();
            int i=0;
            for(String str:logPatterns){
                Map<String,String>temp=new HashMap<>();
                temp.put("field",i+"");
                temp.put("title", i+":"+str);
                headMsg.add(temp);
                //temp2.put(i+"",i+"");
                i++;
            }
            //body.add(temp2);
            queryMap.put("head", headMsg);
            queryMap.put("body", body);
            httpJsonResult.setObj(queryMap);
            return httpJsonResult;
        }else{
            httpJsonResult.setJsonCode(-1);
            httpJsonResult.setJsonMsg("日志格式未配置");
            return httpJsonResult;
        }
    }

    //解析跳转
    @PostMapping("/analysis")
    @ResponseBody
    public HttpJsonResult analysis() throws Exception {
        Map<String,Object> queryMap=new HashMap<>();
        AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
        ShowHeadMsg headMsg=analysisUtil.getHeadMsg();
        HttpJsonResult httpJsonResult=new HttpJsonResult();
        if(null!=headMsg) {
            queryMap.put("headMsg", headMsg);
            httpJsonResult.setObj(queryMap);
        }else{
            httpJsonResult.setJsonCode(-1);
            httpJsonResult.setJsonMsg("为上传文件解析或解析失败!");
        }
        return httpJsonResult;
    }

    /**
     {
     "code": 0,
     "msg": "",
     "count": 1000,
     "data": [{}, {}]
     }
     */
    /**
     * layui 通用返回数据
     * @param result
     * @return
     */
    private  Map<String,Object> getLayuiTable(List result){
        return getLayuiTable(result,result.size());
    }
    private  Map<String,Object> getLayuiTable(List result,int count){
        Map<String,Object> resutMap=new HashMap<>();
        resutMap.put("code",0);
        resutMap.put("count",count);
        resutMap.put("data",result);
        if(result.size()==0){
            resutMap.put("msg","解析数据为空");
        }
        return resutMap;
    }
    @RequestMapping("/urlFilter")
    @ResponseBody
    public Map<String,Object> urlFilter(@ModelAttribute LayuiPage page) throws Exception {
        AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
        ShowHeadMsg headMsg=analysisUtil.getHeadMsg();
        List result=headMsg.getUrlFilterMap();
        //split page
        List subList = (List)result.stream().skip((page.getPage()-1)*page.getLimit()).limit(page.getLimit()).collect(Collectors.toList());
        return getLayuiTable(subList,result.size());
    }
    @RequestMapping("/ipCount")
    @ResponseBody
    public Map<String,Object> ipCount() throws Exception {
        AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
        ShowHeadMsg headMsg=analysisUtil.getHeadMsg();
        return getLayuiTable(headMsg.getIpRequestMap());
    }
    @RequestMapping("/statusCode")
    @ResponseBody
    public Map<String,Object> statusCode() throws Exception {
        AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
        ShowHeadMsg headMsg=analysisUtil.getHeadMsg();
        return getLayuiTable(headMsg.getHttpStatusMap());
    }
    @PostMapping("/search")
    @ResponseBody
    public HttpJsonResult search(@RequestParam(value = "patternSQL",required = true)String patternSQL) throws Exception {
        HttpJsonResult httpJsonResult=new HttpJsonResult();
        try {
            AnalysisUtil analysisUtil = AnalysisUtil.getInstance();
            Map<String, List> queryResult = analysisUtil.search(patternSQL);
            httpJsonResult.setObj(queryResult);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            httpJsonResult.setJsonCode(-1);
            httpJsonResult.setJsonMsg(e.getMessage());
        }
        return httpJsonResult;
    }

    @PostMapping("/rest/billSend")
    @ResponseBody
    public String testErp(@RequestBody String jsonData){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        //设置跨域访问
        //允许跨域的主机地址
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许跨域的请求方法GET, POST, HEAD 等
        response.setHeader("Access-Control-Allow-Methods", "*");
        //重新预检验跨域的缓存时间 (s)
        response.setHeader("Access-Control-Max-Age", "4200");
        //允许跨域的请求头
        response.setHeader("Access-Control-Allow-Headers", "*");
        //是否携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");

      return "{\"return_code\":\"-1\",\"return_msg\":\"\"}";
    }
}
